<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="isLoading"
      :success-text="refreshSuccessText"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <ArticleItem v-for="(item, index) in list" :key="index" :article="item" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from "@/components/article-item";
import { getArticles } from "@/api/article";
export default {
  name: "ArticleList",
  props: {
    channel: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      error: false,
      timestamp: null,
      isLoading: false,
      refreshSuccessText: "",
    };
  },
  components: {
    ArticleItem,
  },
  methods: {
    async onLoad() {
      try {
        // 异步更新数据
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
        });
        this.list.push(...data.data.results);
        // 加载状态结束
        this.loading = false;

        // 如果请求过来的还有数据，更新时间戳，直到请求的数据为空
        if (data.data.results.length && this.list.length < 40) {
          this.timestamp = data.data.pre_timestamp;
        } else {
          this.finished = true;
        }
      } catch (e) {
        this.loading = false;
        this.error = true;
      }
    },
    async onRefresh() {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
        });
        this.list.unshift(...data.data.results);
        this.refreshSuccessText = `刷新成功，更新了${data.data.results.length}条数据！`;
        this.isLoading = false;
      } catch (e) {
        console.log(e);
        this.refreshSuccessText = "刷新失败，请稍后重试!";
        this.isLoading = false;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.article-list {
  height: 80vh;
  overflow-y: auto;
}
</style>